<template>
  <div class="contract-termination">
    <div class="wrap">
      <!-- 顶部步骤条（高亮第3步：解除合同） -->
      <div class="steps">
        <div v-for="(s,i) in steps" :key="i" class="step" :class="{ active: i <= 2 }">
          <div class="dot">{{ i + 1 }}</div>
          <div class="name">{{ s }}</div>
          <div v-if="i < steps.length - 1" class="line" />
        </div>
      </div>

      <div class="content">
        <!-- 左侧：基本信息、申请信息、上传解除协议 -->
        <div class="left">
          <div class="card">
            <div class="card-title">基本信息</div>
            <el-descriptions :column="2" border label-class-name="desc-label" class="desc">
              <el-descriptions-item label="单据编号">{{ formData.elderlyNo }}</el-descriptions-item>
              <el-descriptions-item label="老人姓名">{{ formData.elderlyName }}</el-descriptions-item>
              <el-descriptions-item label="老人身份证号">{{ formData.elderlyIdCard }}</el-descriptions-item>
              <el-descriptions-item label="联系方式">{{ formData.contact }}</el-descriptions-item>
              <el-descriptions-item label="费用期限">{{ formData.feePeriod }}</el-descriptions-item>
              <el-descriptions-item label="护理等级">{{ formData.careLevel }}</el-descriptions-item>
              <el-descriptions-item label="入住床位">{{ formData.bedNumber }}</el-descriptions-item>
              <el-descriptions-item label="签约合同">
                {{ formData.contract }}
                <el-button link type="primary" size="small" style="margin-left: 8px">查看</el-button>
              </el-descriptions-item>
              <el-descriptions-item label="养老顾问">{{ formData.consultant }}</el-descriptions-item>
              <el-descriptions-item label="护理员">{{ formData.caregiver }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="card">
            <div class="card-title">申请信息</div>
            <el-descriptions :column="2" border label-class-name="desc-label" class="desc">
              <el-descriptions-item label="退住日期">{{ formData.checkoutDate }}</el-descriptions-item>
              <el-descriptions-item label="退住原因">{{ formData.checkoutReason }}</el-descriptions-item>
              <el-descriptions-item label="备注" :span="2">
                {{ formData.remark }}
              </el-descriptions-item>
              <el-descriptions-item label="申请人">{{ formData.applicantName }}</el-descriptions-item>
              <el-descriptions-item label="申请时间">{{ formData.submitTime }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="card">
            <div class="card-title">
              <span class="index">1</span>
              上传解除协议
            </div>
            <el-form :model="form" label-width="120px">
              <el-form-item label="合同编号">
                <el-input v-model="form.contractNo" readonly />
              </el-form-item>
              <el-form-item label="解除日期" required>
                <el-date-picker
                  v-model="form.terminationDate"
                  type="date"
                  placeholder="选择解除日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item label="解除协议" required>
                <el-upload
                  class="upload-demo"
                  drag
                  action="#"
                  :auto-upload="false"
                  :limit="1"
                  accept=".pdf"
                >
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>
                  <template #tip>
                    <div class="el-upload__tip">
                      请上传pdf文件，大小在60M以内
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-form>
          </div>

          <div class="bottom-actions">
            <el-button @click="$router.back()">返回</el-button>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
          </div>
        </div>

        <!-- 右侧：操作记录 -->
        <div class="right">
          <div class="card">
            <div class="card-title">操作记录</div>
            <div class="log">
              <div class="log-item">
                <div class="avatar">✓</div>
                <div class="info">
                  <div>护理员a发起申请</div>
                  <div class="sub">护理员a（已发起）</div>
                </div>
                <div class="time">{{ formData.submitTime }}</div>
              </div>
              <div class="log-item">
                <div class="avatar">✓</div>
                <div class="info">
                  <div>（角色）审批·申请审批</div>
                  <div class="sub">退住审批员（已通过）</div>
                </div>
                <div class="time">2048-10-15 09:00:00</div>
              </div>
            </div>
            <div class="approval-comment">
              <el-input
                v-model="approvalComment"
                type="textarea"
                :rows="3"
                placeholder="这里是审批意见。"
                readonly
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { getCheckoutApplicationDetail } from '@/api/system/approval'
import { getContractByElderlyId } from '@/api/system/out_management'

const router = useRouter()
const route = useRoute()

const steps = ['申请退住','申请审批','解除合同','调整账单','账单审批','退住审批','费用清算']

const form = ref({
  contractNo: 'HT2048101015000001',
  terminationDate: new Date().toISOString().split('T')[0] // 设置为当前日期
})

// 基本信息数据
const formData = ref({
  elderlyNo: 'TZ2048101015000001',
  elderlyName: '高启强',
  elderlyIdCard: '230201397072210209',
  contact: '13899888888',
  feePeriod: '2048-10-10 —— 2049-10-10',
  careLevel: '特级护理等级',
  bedNumber: '101床位',
  contract: '高启强长住合同.pdf',
  consultant: '屠延桦',
  caregiver: '盛长松、盛明兰、盛如兰',
  checkoutDate: '2048-10-15',
  checkoutReason: '服务不符',
  remark: '已和家属沟通达成一致，客户回到家后将重新办理入住。',
  applicantName: '屠延桦',
  submitTime: '2048-10-05 15:00:00'
})

const approvalComment = ref('')

// 页面加载时从URL参数查询业务数据
onMounted(async () => {
  console.log('=== 解除合同页面加载开始 ===')
  console.log('URL参数:', route.query)
  console.log('完整路由信息:', route)
  
  // 优先从后端API获取数据（根据业务ID查询）
  console.log('=== 优先从后端API获取数据 ===')
  
  if (route.query.id) {
    const businessId = route.query.id
    console.log('使用业务ID从后端获取数据:', businessId)
    
    try {
      const response = await getCheckoutApplicationDetail(businessId)
      console.log('后端返回的申请详情:', response)
      
      if (response.code === 200 && response.data) {
        const appData = response.data
        console.log('解析后的申请数据:', appData)
        
        // 使用后端数据更新表单
        formData.value = {
          elderlyNo: appData.checkOutNo || 'TZ' + businessId,
          elderlyName: appData.elderlyName || '未知老人',
          elderlyIdCard: appData.elderlyIdCard || '未知身份证',
          contact: appData.elderlyContact || '未知联系方式',
          feePeriod: (appData.feeStartDate && appData.feeEndDate) ? 
            `${appData.feeStartDate} 至 ${appData.feeEndDate}` : '未知费用期限',
          careLevel: appData.careLevel || '未知护理等级',
          bedNumber: appData.bedNumber || '未知床位',
          contract: appData.contractName || '未知合同',
          consultant: appData.caregiverName || '未知顾问',
          caregiver: appData.caregiverName || '未知护理员',
          checkoutDate: appData.checkOutDate || '未知退住日期',
          checkoutReason: appData.checkOutReason || '未知退住原因',
          remark: appData.remark || '无备注',
          applicantName: appData.creatorName || '护理员a',
          submitTime: appData.createTime || new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
          }).replace(/\//g, '-')
        }
        
        // 更新合同编号
        if (appData.contractNo) {
          form.value.contractNo = appData.contractNo
          console.log('合同编号:', appData.contractNo)
        }
        
        console.log('使用后端数据更新表单:', formData.value)
        console.log('合同表单数据:', form.value)
        
        // 如果有老人ID，尝试获取合同信息
        if (appData.elderlyId) {
          try {
            console.log('=== 获取合同信息 ===')
            console.log('老人ID:', appData.elderlyId)
            
            const contractResponse = await getContractByElderlyId(appData.elderlyId)
            console.log('合同API响应:', contractResponse)
            
            if (contractResponse.code === 200 && contractResponse.data) {
              console.log('合同数据:', contractResponse.data)
              if (contractResponse.data.contractName) {
                formData.value.contract = contractResponse.data.contractName
                console.log('合同名称:', contractResponse.data.contractName)
              }
              if (contractResponse.data.contractNo) {
                form.value.contractNo = contractResponse.data.contractNo
                console.log('合同编号:', contractResponse.data.contractNo)
              }
            }
            
            console.log('=== 合同信息获取完成 ===')
          } catch (contractError) {
            console.error('获取合同信息失败:', contractError)
          }
        }
        
        console.log('=== 数据加载完成 ===')
        console.log('最终基本信息数据:', formData.value)
        console.log('最终合同表单数据:', form.value)
      }
    } catch (apiError) {
      console.error('后端API调用失败:', apiError)
    }
  } else {
    console.log('警告：没有业务ID参数')
  }
  
  console.log('=== 解除合同页面加载完成 ===')
})

// 提交处理
const handleSubmit = () => {
  // 这里可以添加表单验证逻辑
  ElMessage.success('解除合同提交成功！')
  
  // 跳转到解除合同处理页面
  router.push('/tuizhuceshi/jiechuhetongchuli')
}
</script>

<style scoped>
.contract-termination{background:#f5f6f8;min-height:100vh}
.wrap{max-width:1200px;margin:0 auto;padding:14px 12px}
.steps{display:flex;align-items:center;background:#fff;border:1px solid #ebeef5;border-radius:4px;padding:10px 12px;margin-bottom:14px}
.step{display:flex;align-items:center;color:#a8abb2}
.dot{width:24px;height:24px;border-radius:50%;border:2px solid #dcdfe6;display:flex;align-items:center;justify-content:center;margin-right:6px}
.step.active .dot{border-color:#409eff;color:#409eff}
.name{margin-right:8px}
.line{width:56px;height:1px;background:#e9eaef;margin:0 8px}
.content{display:flex;gap:12px}
.left{flex:1.3}
.right{flex:1}
.card{background:#fff;border:1px solid #ebeef5;border-radius:4px;padding:12px 14px;margin-bottom:12px}
.card-title{font-weight:600;color:#303133;margin-bottom:10px;display:flex;align-items:center}
.index{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:50%;background:#ff5b5b;color:#fff;font-size:12px;margin-right:8px}
.desc{--el-description-table-border-color:#ebeef5}
.desc-label{width:120px}
.log-item{display:flex;align-items:flex-start;padding:10px 0;border-bottom:1px dashed #f0f0f0}
.log-item:last-child{border-bottom:none}
.avatar{width:22px;height:22px;border-radius:50%;background:#67c23a;color:#fff;display:flex;align-items:center;justify-content:center;margin-right:8px;margin-top:2px;font-size:12px}
.info .sub{font-size:12px;color:#909399}
.time{margin-left:auto;color:#909399;font-size:12px}
.approval-comment{margin-top:12px}
.bottom-actions{display:flex;justify-content:center;gap:12px;align-items:center;margin-top:20px}
</style>

